package hu.bme.gabor.onlab;

import java.util.Iterator;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;

public class Settings extends PreferenceActivity implements
		OnSharedPreferenceChangeListener {
	public static final String PREF_SERVER_NAME = "PREF_SERVER_NAME";
	public static final String PREF_GOOGLE_ACCOUNTS = "PREF_GOOGLE_ACCOUNTS";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.pref);

		Context context = getApplicationContext();
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		prefs.registerOnSharedPreferenceChangeListener(this);
		
		ListPreference listPreferenceCategory = (ListPreference) findPreference("PREF_GOOGLE_ACCOUNTS");
		if (listPreferenceCategory != null) {

			CharSequence entries[] = new String[MainActivity.getGoogleAccounts().size()];
		    CharSequence entryValues[] = new String[MainActivity.getGoogleAccounts().size()];

		    int i = 0;
		    
		    for(Iterator<String> iter = MainActivity.getGoogleAccounts().iterator(); iter.hasNext(); i++){
		        entries[i] = iter.next();
		        entryValues[i] = Integer.toString(i);
		    }
		    listPreferenceCategory.setEntries(entries);
		    listPreferenceCategory.setEntryValues(entryValues);
 
	        ListPreference listPref = (ListPreference) findPreference("PREF_GOOGLE_ACCOUNTS");
	        listPref.setSummary(listPref.getEntry());
	        MainActivity.googleAccount = (String) listPref.getEntry();
	        EditTextPreference listPrefwww = (EditTextPreference) findPreference("PREF_SERVER_NAME");
	        listPrefwww.setSummary(listPrefwww.getText());
		}
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
		ListPreference listPref = (ListPreference) findPreference("PREF_GOOGLE_ACCOUNTS");
        listPref.setSummary(listPref.getEntry());
        MainActivity.googleAccount = (String) listPref.getEntry();
        EditTextPreference listPrefwww = (EditTextPreference) findPreference("PREF_SERVER_NAME");
        listPrefwww.setSummary(listPrefwww.getText());
	}
}